// login.js
const app = getApp()
import { requestApi } from '../../../api'
import { extend } from '../../../sdk/extend'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        protocolContent: [],
        encryptedData: '',
        openid: '',
        session_key: '',
        isCheckedProtocol: false,
        newUserReceivePrice: app.data.newUserPop && app.data.newUserPop.price || ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        this.getProtocolContent();
    },

    onShow() {
        const self = this;
        wx.login({
            success(res) {
                app.request({
                    url: requestApi.getKey,
                    method: 'POST',
                    login: false,
                    data: {
                        js_code: res.code
                    },
                }, (data) => {
                    if (data.original.ret_code == 200) {
                        self.setData({
                            session_key: data.original.data.session_key,
                            openid: data.original.data.openid
                        })
                    }
                }, (error) => {
                    wx.showModal({
                        title: '提示',
                        showCancel: false,
                        content: error,
                    })
                })
            }
        })
    },

    getProtocolContent: function () {
        app.request({
            url: requestApi.getProtocolContentUrl,
            login: false,
            data: {
                protocol_name: 'login_account'
            },
        }, (data) => {
            this.setData({
                protocolContent: data.original.data
            })
        }, (error) => {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        })
    },

    // 跳转协议页面
    readPurchaseNotes: function (e) {
        let protocolName = e.currentTarget.dataset.protocol
        let url = `/pages/goods/purchaseNotes/purchaseNotes?protocol_name=${protocolName}`

        wx.navigateTo({
            url: url,
        })
    },
    checkedProtocol(e) {
        const isChecked = e.detail.value.find(item => item == 'protocol');
        let isCheckedProtocol = false;

        if (isChecked) {
            isCheckedProtocol = true;
        } else {
            isCheckedProtocol = false;
        }

        this.setData({
            isCheckedProtocol
        })
    },
    // 微信手机号快捷登录
    getPhoneNumber(e) {
        const { session_key, openid } = this.data;

        app.request({
            url: requestApi.getdecryption,
            method: 'POST',
            login: false,
            data: {
                encryptData: e.detail.encryptedData,
                iv: e.detail.iv,
                session_key: session_key
                // encryptData: encodeURIComponent(e.detail.encryptedData),
                // iv: encodeURIComponent(e.detail.iv),
                // session_key: encodeURIComponent(data.original.data.session_key)
            },
        }, (d) => {
            if (d.original.ret_code == 200) {
                wx.showLoading({title: '登录中...'});

                app.request({
                    url: requestApi.phoneLogin,
                    
                    method: 'POST',
                    login: false,
                    data: {
                        countryCode: d.original.data.wx_return.countryCode,
                        phoneNumber: d.original.data.wx_return.phoneNumber,
                        seller_uid: wx.getStorageSync('seller_uid') || '',
                        session_key: session_key,
                        openid_mf: openid,
                        unionid_mf: '' // 测试TODO
                    },
                }, (r) => {
                    
                    wx.hideLoading();

                    if (r.original.ret_code == 200) {
                        var userinfo = wx.getStorageSync('userinfo') || {}
    
                        userinfo = extend(true, {}, userinfo, { 'openid': openid})
                        wx.setStorageSync('userinfo', userinfo);

                        if (app.data.newUserPop && app.data.newUserPop.coupon_no) {
                            this.receiveCoupon();
                        } else {
                            wx.showToast({
                                title: '登录成功！',
                                duration: 1000,
                            })
                            
                            wx.navigateBack();
                        }
                    }
                }, (error) => {
                    wx.showModal({
                        title: '提示',
                        showCancel: false,
                        content: error,
                    })
                })
            }
        }, (error) => {
            // wx.showModal({
            //     title: '提示',
            //     showCancel: false,
            //     content: error,
            // })
        })
    },
    // 跳转到手机号登录
    goCodePage() {
        const { isCheckedProtocol } = this.data;

        if(!isCheckedProtocol) {
            wx.showToast({
                title: '请先阅读并同意《迷橙用户服务协议》',
                icon: 'none'
            })
        } else {
            wx.navigateTo({
                url: '../phone/phone',
            })
        }
    },

    // 新手优惠，一键领取优惠券
    receiveCoupon() {
        const { channel  } = this.data;
        
        app.request({
            url: requestApi.receiveCoupon,
            data: {
                is_new_ver: true,
                coupon_no: app.data.newUserPop.coupon_no,
                channel: channel
            },
        }, (data) => {
            wx.showToast({
                title: '登录成功，开启购物之旅，好礼将在1-2分钟内发放至您的优惠券账户',
                duration: 1000,
            })
        }, (error) => {
            // 
        }, () => {
            wx.navigateBack();
        })
    },
})